package com.cm.projectx.controller.analysis.aspect;

import cn.hutool.json.JSONUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.cm.projectx.common.cache.SystemOrgCache;
import com.cm.projectx.entity.analysis.RespDto;
import com.cm.projectx.response.Result;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

@Aspect
@Component
public class ResponseAspect {
    private Log log = LogFactory.get();
    @Around("execution(* com.cm.projectx.controller.analysis..*(..))")
    public Object wrapResponse(ProceedingJoinPoint joinPoint) throws Throwable {
        // 执行原方法
        //{
        //  "code": 0,
        //  "msg": "业务成功",
        //  "data": {
        //    "monitorPointResult": [
        //      {
        //        "name": "博兴县农贸采价点",
        //        "id": "1_39"
        //      },
        //      {
        //        "name": "惠民县农贸采价点",
        //        "id": "1_40"
        //      }
        //    ],
        //    "reportType": "T001",
        //    "priceResult": [
        //      {
        //        "avgSuperPrice": "1593.50",
        //        "no": 1,
        //        "1_40MarketPrice": 750.0, // （规则：监测点id+MarketPrice）
        //        "unit": "元/台",
        //        "priceAlarmPercent": "35%",
        //        "scheduleType": "单次",
        //        "1_39SuperPrice": 1200.0, // （规则：监测点id+SuperPrice）
        //        "kind": "长虹液晶32寸",
        //        "1_40SuperPrice": 1987.0, // （规则：监测点id+SuperPrice）
        //        "1_39MarketPrice": 1800.0, // （规则：监测点id+MarketPrice）
        //        "name": "彩电",
        //        "avgMarketPrice": "1275.00"
        //      },
        //      {
        //        "avgSuperPrice": "1328.00",
        //        "no": 2,
        //        "1_40MarketPrice": 600.0,
        //        "unit": "元/台",
        //        "priceAlarmPercent": "90%",
        //        "scheduleType": "单次",
        //        "1_39SuperPrice": 1400.0,
        //        "kind": "海尔1.5匹冷暖",
        //        "1_40SuperPrice": 1256.0,
        //        "1_39MarketPrice": 1999.0,
        //        "name": "空调机",
        //        "avgMarketPrice": "1299.50"
        //      }
        //    ]
        //  }
        //}
        Object result = joinPoint.proceed();
        System.out.println(result instanceof Result);
        if (Objects.nonNull(result) && result instanceof Result) {
            log.error(JSONUtil.toJsonStr(result));
            Result newResult = (Result) result;
            List<RespDto> priceResult = (List<RespDto>) newResult.getData().get("priceResult");
            List<String> monitorList = (List<String>) newResult.getData().get("monitorSet");
            List<HashMap<String, String>> dataMap = new ArrayList<>();
            AtomicBoolean initOrg = new AtomicBoolean(false);

            List<HashMap<String, String>> monitorListMap = new ArrayList<>();
            if (Objects.nonNull(monitorList) && !monitorList.isEmpty()) {
                newResult.addData("monitorPointResult", monitorList.stream().map(
                        monitor -> {
                            HashMap<String, String> map = new HashMap<>();
                            map.put("id", monitor);
                            map.put("name", SystemOrgCache.getOrgName(monitor));
                            return map;
                        }
                ).collect(Collectors.toList()));
                initOrg.set(true);
            } else {
                initOrg.set(false);
                newResult.addData("monitorPointResult", monitorListMap);
            }
            if (Objects.nonNull(newResult.getData().get("needMutiTableTitle")) && (boolean) newResult.getData().get("needMutiTableTitle")) {
                //需要对结果二次分组，汇聚指标到同一行
                Map<String, List<RespDto>> secondMap = priceResult.stream()
                        .collect(Collectors.groupingBy(RespDto::getProductName));
                secondMap.forEach((key, value) -> {
                    //key  商品名称   value   分组list
                    RespDto item = value.get(0);
                    HashMap<String, String> oneMap = new HashMap<>();
                    oneMap.put("name", item.getProductName());
                    oneMap.put("unit", item.getProductUnit());
                    oneMap.put("kind", item.getProductLevel());
                    oneMap.put("floatValue", item.getFloatValue());
                    oneMap.put("priceType", item.getPriceType());
                    oneMap.put("frequency", item.getFrequency());
                    value.forEach(detail -> {
                        oneMap.put("circle" + detail.getPriceType(), detail.getCircleValues().get(0).getValue());
                        oneMap.put("last" + detail.getPriceType(), detail.getLastMetrics().get(0).getValue());
                        oneMap.put("now" + detail.getPriceType(), detail.getNowMetrics().get(0).getValue());
                        detail.getMonitorPriceMapList().forEach((orgId, valueMap) -> {
                            oneMap.put(orgId + detail.getPriceType(), valueMap.get(0).getValue());
                        });
                    });
                    dataMap.add(oneMap);
                });
            } else {
                priceResult.forEach(item -> {
                    HashMap<String, String> oneMap = new HashMap<>();
                    oneMap.put("name", item.getProductName());
                    oneMap.put("unit", item.getProductUnit());
                    oneMap.put("kind", item.getProductLevel());
                    oneMap.put("floatValue", item.getFloatValue());
                    oneMap.put("priceType", item.getPriceType());
                    oneMap.put("frequency", item.getFrequency());
                    if (item.getCircleValues().size() > 1) {
                        item.getCircleValues().forEach(circle -> {
                            if (circle.getName().contains("(")) {
                                oneMap.put("circle" + circle.getName().substring(2).substring(1, 5), circle.getValue());
                            } else {
                                oneMap.put("circle" + circle.getName(), circle.getValue());
                            }
                        });
                    } else {
                        oneMap.put("circleValues", item.getCircleValues().get(0).getValue());
                    }
                    if (item.getLastMetrics().size() > 1) {
                        item.getLastMetrics().forEach(lastMetric -> {
                            if (lastMetric.getName().contains("(")) {
                                oneMap.put("last" + lastMetric.getName().substring(0, 4), lastMetric.getValue());
                            } else {
                                oneMap.put("last" + lastMetric.getName(), lastMetric.getValue());
                            }
                        });
                    } else {
                        oneMap.put("lastMetrics", item.getLastMetrics().get(0).getValue());
                    }
                    if (item.getNowMetrics().size() > 1) {
                        item.getNowMetrics().forEach(nowMetric -> {
                            if (nowMetric.getName().contains("(")) {
                                oneMap.put("now" + nowMetric.getName().substring(0, 4), nowMetric.getValue());
                            } else {
                                oneMap.put("now" + nowMetric.getName(), nowMetric.getValue());
                            }
                        });
                    } else {
                        oneMap.put("nowMetrics", item.getNowMetrics().get(0).getValue());
                    }
                    item.getMonitorPrices().forEach(monitorPrice -> {
                        oneMap.put(monitorPrice.getName() + "Price", monitorPrice.getValue());
                    });
                    item.getMonitorPriceMapList().forEach((key, value) -> {
                        if (value.size() > 1) {
                            value.forEach(monitorPrice -> {
                                oneMap.put(key + monitorPrice.getName(), monitorPrice.getValue());
                            });
                        } else {
                            value.forEach(monitorPrice -> {
                                oneMap.put(key + "Price", monitorPrice.getValue());
                            });
                        }
                        if (!initOrg.get()) {
                            HashMap<String, String> map = new HashMap<>();
                            map.put("id", key);
                            map.put("name", SystemOrgCache.getOrgName(key));
                            monitorListMap.add(map);
                        }
                    });
                    initOrg.set(true);
                    dataMap.add(oneMap);
                });
            }
            newResult.addData("priceResult", dataMap);
            log.error(JSONUtil.toJsonStr(newResult));
            return newResult;
        }
        // 包装返回结果
        return result;
    }
}